package tool

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

// SendPostFormUrlEncoded 发送三方http post请求application/x-www-form-urlencoded方式
func SendPostFormUrlEncoded(targetURL string, data map[string]any) (string, error) {

	// Convert data to JSON first
	jsonData, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	// Decode JSON into a map[string]string for url.Values compatibility
	var stringData map[string]string
	err = json.Unmarshal(jsonData, &stringData)
	if err != nil {
		return "", err
	}
	// Now create url.Values from the stringData map
	formData := url.Values{}
	for key, val := range stringData {
		formData.Add(key, val)
	}
	body := formData.Encode()

	// Create a new HTTP request with form data
	req, err := http.NewRequest(http.MethodPost, targetURL, bytes.NewBufferString(body))
	if err != nil {
		return "", err
	}

	// Set the appropriate headers for x-www-form-urlencoded content
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("requestid", "350a1abf-3387-11ef-b22e-35ccf23fad77")

	// Create a new HTTP client and send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	// Read the response body
	bodyResp, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resStr := string(bodyResp)
	// Log the request and response
	fmt.Printf("Target URL: %s\nData: %s\nResponse: %s\n", targetURL, body, resStr)

	return resStr, nil
}

func SendPostJson(targetURL string, data map[string]interface{}) (string, error) {
	// Convert data to JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		return "", err
	}
	// Create a new HTTP request
	req, err := http.NewRequest(http.MethodPost, targetURL, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}

	// Set the appropriate headers
	req.Header.Set("Content-Type", "application/json")

	// Create a new HTTP client and send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	resStr := string(body)

	// Log the request and response
	fmt.Printf("URL: %s\nData: %s\nResponse: %s\n", targetURL, string(jsonData), resStr)

	return resStr, nil
}
